//
//  MTInputPasswordView.m
//  MeToo
//
//  Created by 俊松何 on 2018/7/17.
//  Copyright © 2018年 tianxie. All rights reserved.
//

#import "MTInputPasswordView.h"

@interface MTInputPasswordView ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIButton *button1;
@property (weak, nonatomic) IBOutlet UIButton *button2;
@property (weak, nonatomic) IBOutlet UIButton *button3;
@property (weak, nonatomic) IBOutlet UIButton *button4;
@property (weak, nonatomic) IBOutlet UIButton *button5;
@property (weak, nonatomic) IBOutlet UIButton *button6;
@property (weak, nonatomic) IBOutlet UITextField *textField;



@property(nonatomic,strong) NSArray *buttons;

@property(nonatomic,copy) NSString *currentPassword;
@end


@implementation MTInputPasswordView



+(instancetype)inputPasswordView
{
    MTInputPasswordView *view = [[NSBundle mainBundle] loadNibNamed:@"MTInputPasswordView" owner:nil options:nil].firstObject;
    return view;
}




- (void)awakeFromNib
{
    [super awakeFromNib];
    _textField.delegate = self;
    _buttons = @[_button1,_button2,_button3,_button4,_button5,_button6];
    @weakify(self);
    [_textField.rac_textSignal subscribeNext:^(NSString * _Nullable text) {
        NSLog(@"-------%@",text);
        @strongify(self);
        self.currentPassword = text;
         [self setPlaceHolder:text];
        if(text.length == 6)
        {
            if (self.completeBlock != nil)
            {
                self.completeBlock(text);
            }
        }
    }];
}

-(void)setPlaceHolder:(NSString *)string
{
    if(string == nil)
    {
        [self clearPassword];
    }
    for (UIButton *button in self.buttons) {
        [button setImage:nil forState:UIControlStateNormal];
    }
    
    int count = (int)[string length];
    int index = 0;
    for (int i = 0; i < count; i++) {
        UIButton *button = self.buttons[i];
        index = i + 1;
        [button setImage:[UIImage imageNamed:@"passwordHolder"] forState:UIControlStateNormal];
    }
    
    for (int j = index; j < count; j++) {
        UIButton *button = self.buttons[j];
        index = j;
       [button setImage:nil forState:UIControlStateNormal];
    }
}
-(void)clearPassword
{
    self.currentPassword = @"";
    self.textField.text = @"";
    for (UIButton *button in self.buttons) {
        [button setImage:nil forState:UIControlStateNormal];
    }
}

- (IBAction)butClick:(UIButton *)sender {
    [self.textField becomeFirstResponder];
}
-(void)becomeFirstResponder
{
    [self.textField becomeFirstResponder];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSInteger maxLength = 6;
    return ((range.location + string.length) <= maxLength);
}


@end
